/**
 * Created by apple on 2017/7/3.
 */

var DBFactory = require('../db/mysql_db');
var async = require('async');
var Config =require('../config');
var GlobalVar = require('../global_var');
var UserCashDao = module.exports;
var XingetApp = require('../XingetApp');

//用户余额及账户查询
UserCashDao.userAccountInfo = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    var sql = "select uaa.money,u.ali_account,u.wx_account from users u " +
        "left join user_app_new_agent uaa on u.uid = uaa.uid where u.uid = ? and uaa.app_sid = ? ";
    DBFactory.poolQuery(sql, [data.uid,data.app_sid],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null, result);
        }
    );

}

//申请提现
UserCashDao.addCashApply = function (data, cb) {

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            //判断余额是否充足,账号是否正确
            function (callback) {
                var sql = "select uaa.money,u.ali_account,u.wx_account,u.real_name,uaa.cash_status from users u " +
                    "left join user_app_new_agent uaa on u.uid = uaa.uid where u.uid = ? and uaa.app_sid = ? ";
                var value = [data.uid,data.app_sid];
                connection.query(sql, value, function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    var userInfo = (result && result.length > 0) ? result[0] : undefined;
                    if (userInfo.money < data.cash) {
                        callback('余额不足');
                        return;
                    }
                    if (userInfo.cash_status == 0) {
                        callback('抱歉，您的提现权限已被关闭');
                        return;
                    }
                    if (data.cash_type == 12 && userInfo.ali_account != data.plat_account) {
                        callback('提现账户有误');
                        return;
                    }
                    if (data.cash_type == 13 && userInfo.wx_account != data.plat_account) {
                        callback('提现账户有误');
                        return;
                    }
                    callback(null, userInfo);
                });
            },

            //余额充足，扣余额
            function (userInfo, callback) {
                if (!userInfo) {
                    callback('操作失败');
                    return;
                }

                connection.query('update user_app_new_agent set money = money - ? where uid = ? and app_sid = ? ', [data.cash, data.uid,data.app_sid], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, userInfo);
                        return;
                    }
                    callback('操作失败');
                });
            },


            //创建订单
            function (userInfo, callback) {
                if (!userInfo) {
                    callback('操作失败');
                    return;
                }

                var cashInfo = {
                    user_account: data.user_account,
                    plat_account: data.plat_account,
                    money: userInfo.money,
                    cash: data.cash,
                    cash_type: data.cash_type,
                    app_sid: data.app_sid,
                    real_name: userInfo.real_name,
                    amount:data.amount ? data.amount : data.cash,
                    type: (data.type && parseInt(data.type) < 50) ? data.type : 12,
                };
                connection.query('insert into user_cash set ? ', [cashInfo], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows <= 0) {
                        callback('操作失败');
                        console.log('插入user_cash表失败')
                        return;
                    }
                    userInfo.order_id = '02' + result.insertId;
                    userInfo.cash_id = result.insertId;
                    callback(null, userInfo);
                });
            },


            //记录下扣余额的操作
            function (userInfo, callback) {
                if (!userInfo) {
                    callback('操作失败');
                    console.log('用户提现时更新users表失败');
                    return;
                }
                var userMoneyInfo = {
                    order_id:userInfo.order_id,
                    uid: data.uid,
                    original_money: userInfo.money,
                    money: data.cash,
                    comment: '提现申请',
                    app_sid:data.app_sid,
                    sign: 1,
                    type: (data.type && data.type < 50) ? data.type : 12,
            };
                connection.query('INSERT INTO user_money SET ? ', [userMoneyInfo], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, userInfo);
                        return;
                    }
                    callback('操作失败');
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        if (data.isFree) autoPayMoney({id:res.cash_id});
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}

function autoPayMoney(data,cb) {
    var appTime = new Date().getTime();
    var param = {
        uc_id:data.id,
        app_time:appTime,
        app_key:Config.USUZ_KEY,
        app_sign:getAppSign(Config.USUZ_KEY,GlobalVar.apps[Config.USUZ_KEY],appTime),
    };
    baseRequest('http://' + Config.USUZHost, '/payment/transToAcc', param, function(err, data){
        if(err) {
            console.log('autoPayMoney err:' + err);
        }
        console.log('自动打款成功，cash_id:' + param.id + ' time:' + appTime);
    });
}

//管理员操作用户提现
UserCashDao.handleCashApply = function (data, cb) {

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            //查看该订单，并确定提现金额
            function (callback) {
                connection.query('select * from user_cash where id = ? ', [data.id], function (err, result) {
                    var cashInfo = (result && result.length > 0) ? result[0] : undefined;
                    if (!cashInfo) {
                        callback('未查询到该订单');
                        return;
                    }
                    if (cashInfo.status != 12) return callback('重复操作');//防止多次更改
                    if (data.app_sid && cashInfo.app_sid != data.app_sid) return (callback('无操作权限'));
                    callback(null, cashInfo);
                });
            },

            function (cashInfo,callback) {
                connection.query('SELECT uid,money,agent_2 From user_app_new_agent where account = ? and app_sid = ? ', [cashInfo.user_account,cashInfo.app_sid], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    var userInfo = (result && result.length > 0) ? result[0] : undefined;
                    if (!userInfo) {
                        callback('用户不存在');
                        console.log('操作提现状态时，查询不到用户');
                        return;
                    }
                    if (data.taoke_account && userInfo.agent_2 != data.taoke_account){
                        callback('无操作权限');
                        return;
                    }
                    var res = {
                        cashInfo:cashInfo,
                        userInfo:userInfo,
                    }
                    callback(null,res)

                });
            },

            //操作提现订单状态
            function (res, callback) {

                var comment = data.status == 13 ? data.comment : null;

                connection.query('update user_cash set status  = ?,comment = ?,end_time = NOW() where id = ? ', [data.status, comment, data.id], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows <= 0) {
                        callback('操作失败');
                        console.log('更改user_cash表失败')
                        return;
                    }
                    callback(null, res);
                });
            },

            //若审核失败，余额退回,操作users表
            function (res, callback) {
                if (!res || !res.userInfo || !res.cashInfo) return callback('操作失败');
                //如果是审核失败,退回余额
                if (data.status == 13) {

                    //构造余额记录信息
                    var moneyInfo = {
                        uid: res.userInfo.uid,
                        original_money: res.userInfo.money,
                        money: res.cashInfo.cash,
                        comment: '提现审核失败退回',
                        app_sid: res.cashInfo.app_sid,
                        sign: 0,
                        type: res.cashInfo.type
                    };
                    UserCashDao.cashBack(moneyInfo, connection, function (err) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        callback(null, res.cashInfo);
                    });


                } else {

                    callback(null, res.cashInfo)

                }

            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                        var param = {
                            app_sid:data.app_sid,
                            status:data.status,
                            comment:data.comment,
                            account:res.user_account,
                            cash:res.cash
                        };
                        pushAppCashSuccess(param,function () {});
                    }
                });
            }
        });

    });

}

//{app_sid,status,comment,account,message,cash}
function pushAppCashSuccess(data,cb) {
    if (data.app_sid != Config.USUZ_KEY) return;
    var message = '';
    if (data.status == 13) {
        message += '抱歉，您有一笔提现因:"' + data.comment + '"审核未通过，请更正后再试哦～';
    }
    if (data.status == 14) {
        message += '恭喜，您的一笔金额为' +  data.cash + '元的提现已到账，请注意查收哦~';
    }
    XingetApp.pushSimple2Account(data.app_sid, data.user_account, message, function (err, msg) {
        console.log(err + msg);
        cb(err,msg);
    });
}

//提现退回记录
UserCashDao.cashBack = function (moneyInfo, connection, cb) {

    connection.query('update user_app_new_agent set money = money + ? where uid = ? and app_sid = ? ', [moneyInfo.money, moneyInfo.uid,moneyInfo.app_sid], function (err, result) {
        if (err) {
            console.log(err);
            cb(err);
            return;
        }
        if (result.affectedRows <= 0) {
            cb('操作失败');
            console.log('更新users表失败')
            return;
        }

        connection.query('INSERT INTO user_money SET ? ', [moneyInfo], function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            if (result.affectedRows > 0) {
                cb(null);
                return;
            }
            cb('操作失败');
            console.log('插入user_money表失败');
        });
    });
}

//用户提现记录列表
UserCashDao.cashList = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        var baseSql = '';

        var value = [];

        if (data.taoke_account) {
            baseSql += ' inner join user_app_new_agent b on a.user_account = b.account and a.app_sid = b.app_sid where b.app_sid = ? and b.agent_2 = ? ';
            value.push(data.app_sid,data.taoke_account);
        } else {
            if (data.isAdmin) {
                baseSql += ' inner join user_app_new_agent b on a.user_account = b.account and a.app_sid = b.app_sid' +
                    ' where ';
                if (data.open_shop) {
                    baseSql += " b.app_sid LIKE '" + data.app_sid + "_%' ";
                } else {
                    baseSql += ' b.app_sid = ? ';
                    value.push(data.app_sid);
                }
                baseSql += ' AND (isnull(b.agent_2) or b.agent_2 != ? ) ';
                value.push(Config.TAOKE_ACCOUNT);
            }
        }
        if (data.startTime && data.endTime) {
            data.startTime += ' 00:00:00';
            data.endTime += ' 23:59:59';
            baseSql += value.length > 0 ? 'and a.created_time >= ? and a.created_time <= ? ' :
                'where a.created_time >= ? and a.created_time <= ? ';
            value.push(data.startTime);
            value.push(data.endTime);
        } else if (data.startTime) {
            var startTime = data.startTime + ' 00:00:00';
            var endTime = data.startTime + ' 23:59:59';
            baseSql += value.length > 0 ? 'and a.created_time >= ? and a.created_time <= ? ' :
                'where a.created_time >= ? and a.created_time <= ? ';
            value.push(startTime);
            value.push(endTime);
        }
        if (data.status) {
            baseSql += value.length > 0 ? 'and a.status = ? ' : 'where a.status = ? ';
            value.push(data.status);
        }
        if (data.user_account) {
            baseSql += value.length > 0 ? 'and a.user_account like ? ' : 'where a.user_account like ? ';
            value.push('%' + data.user_account + '%');
        }

        var sql = 'SELECT a.* FROM user_cash a ' + baseSql;
        var countSql = 'SELECT COUNT(*) as totalCount,sum(a.cash) as totalMoney FROM user_cash a ' + baseSql;
        var pageNum = data.pageNum ? data.pageNum : 10;
        var page = data.page ? data.page : 1;
        sql += 'limit ' + (page - 1) * pageNum + ',' + pageNum;
        connection.query(sql, value, function (err, result) {
            if (err) {
                cb(err);
                connection.release();
                return;
            }
            var list = {};
            list.cashList = result;
            connection.query(countSql, value, function (e, res) {
                if (e) {
                    connection.release();
                    cb(e);
                    return;
                }
                list.totalCount = ( res && res[0] ) ? res[0].totalCount : 0;
                list.totalMoney = ( res && res[0] ) ? res[0].totalMoney : 0;
                cb(null, list);
                connection.release();
            });
        });
    });
};

//查看当前余额
UserCashDao.getMoney = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    var sql = 'SELECT money,freeze_money FROM user_app_new_agent WHERE uid = ? AND app_sid = ? ';
    var value = [data.uid,data.app_sid];
    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var moeny = (result && result[0]) ? result[0] : {money:0,freeze_money:0};
            cb(null, moeny);
        }
    );

}

//是否能提现
UserCashDao.canDraw = function (data,cb) {
    if (!data.account || !data.uid || !data.app_sid) return cb('参数有误');
    if (data.type) return cb(null,{canDraw:true});
    if (!Config.IS_CASH_LIMIT) {
        var time = new Date();
        var day = time.getDate();
        if (day < 21 || day > 27) {
            cb('非提现日，提现开放日为21日～27日');
            return ;
        }
        return cb(null,{canDraw:true});
    }

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        getFreeOrderMoney(data,connection,function (err,result) {
            if (err) {
                cb(err);
                connection.release();
                return;
            }
            var freeOrderMoney = result.freeOrderMoney;

            judgeUserVipAndGetInfo(data,connection,function (err,result) {
                if (err) {
                    cb(err);
                    connection.release();
                    return;
                }
                var userInfo = result.userInfo;
                if (freeOrderMoney <= 0) {
                    var err = judgeIsCashDay({agent_2:userInfo.agent_2}).err;
                    if (err) {
                        cb(err);
                        connection.release();
                        return
                    }
                }
                var sql1 = " SELECT sum(cash) as cash,sum(amount) as amount FROM user_cash WHERE user_account = ? AND app_sid = ? AND status != 13 ";
                connection.query(sql1, [data.account,data.app_sid], function (e, result) {
                    if (e) {
                        connection.release();
                        cb(e);
                        return;
                    }
                    connection.release();
                    var userCashInfo = (result && result[0]) ? result[0] : undefined;
                    var totalCash = userCashInfo.cash ? userCashInfo.cash : 0;
                    var totalAmount = userCashInfo.amount ? userCashInfo.amount : 0;
                    if (freeOrderMoney > 0 && (totalCash + parseFloat(data.cash)) <= 10){
                        cb(null,{canDraw:true,isFree:true});
                        return;
                    }
                    var err = judgeIsCashDay({agent_2:userInfo.agent_2}).err;
                    if (err){
                        cb(err);
                        return;
                    }
                    if (userInfo.pre_agent_lvl) {
                        getIsLimitCashAgent({totalCash:totalCash,totalAmount:totalAmount,cash:data.cash,uid:data.uid},cb);
                        return;
                    }
                    if (userInfo.vip_sid) return cb(null,{canDraw:true});//会员以上暂无限制

                    if (userInfo.agent_2 == Config.TAOKE_ACCOUNT) return cb(null,{canDraw:true});
                    if ((totalCash + parseFloat(data.cash)) <= 100) {
                        cb(null,{canDraw:true});
                    }else {
                        var beyoundMoney = 100 - totalCash > 0 ? 100 - totalCash : 0;
                        cb('抱歉！您的提现额度只剩' + beyoundMoney + '元，请升级后再提交申请哦~');
                    }
                });

            });
        });
    });
}

function getFreeOrderMoney(data,connection,cb) {
    var sql1 = 'SELECT sum(money) as freeOrderMoney FROM user_money WHERE uid = ? AND app_sid = ? AND type = 15 ';
    var value1 = [data.uid,data.app_sid];
    connection.query(sql1, value1, function (err, result) {
        if (err) {
            cb(err);
            return;
        }
        var freeOrderMoney = result[0].freeOrderMoney;
        cb(null,{freeOrderMoney:freeOrderMoney});
    });
}

function judgeUserVipAndGetInfo(data,connection,cb) {
    var sql = " SELECT uaa.pre_agent_lvl,uaa.agent_2,uv.vip_sid,uaa.cash_status FROM user_app_new_agent uaa " +
        " LEFT JOIN user_vip uv ON uaa.uid = uv.uid AND uaa.app_sid = uv.app_sid " +
        " WHERE uaa.app_sid = ? AND uaa.uid = ? ";
    var value = [data.app_sid,data.uid];
    connection.query(sql, value, function (err, result) {
        if (err) {
            cb(err);
            return;
        }
        var userInfo = (result && result[0]) ? result[0] : undefined;
        if (!userInfo) return cb('不存在该用户');
        if (data.type != 19 && data.cash % 5 != 0) return cb('提现金额要是5的整数倍哦～');
        if (data.type == 19 && data.cash < 1) return cb('单次提现金额需大于1元哦～');
        if (userInfo.cash_status != 1) return cb('抱歉，您的账号暂时无法提现，有疑问请联系客服');
        cb(null,{userInfo:userInfo});
    });
}

function judgeIsCashDay(data) {
    if(data.agent_2 != Config.TAOKE_ACCOUNT) return {};
    var time = new Date();
    var day = time.getDate();
    if (day != 11 && day != 21 && day != 29) {
        return {err:'非提现日，开放日为11、21、29'};
    }
    return {};
}

function getIsLimitCashAgent(data,cb) {
    var param = {};
    param.app_time = new Date().getTime();
    param.app_key = 'usuz';
    param.app_sign = getAppSign(param.app_key,GlobalVar.apps[param.app_key],param.app_time);
    param.uid = data.uid;
    baseRequest('http://' + Config.USUZHost, '/agency_management/getIsWorkAgent', param, function(err, result){
        if(err) {
            cb('抱歉！系统临时错误,请您联系客服处理');
            return;
        }
        if (!result.isWorkAgent) {//非合作代理，可以直接返还成功让提现
            cb(null,{canDraw:true});
            return;
        }
        if (result.agent_status == 3) {
            cb('非常抱歉，在您体验加盟商待遇期间暂时不可提现哦');
            return;
        }
        var limit_cash_ratio = result.limit_cash_ratio;
        var limit_cash_amount = result.limit_cash_amount;
        if (limit_cash_ratio < 0 || limit_cash_ratio > 1){
            cb('抱歉！系统设置错误,请您联系客服处理');
            return;
        }
        //是合作代理商，判断下是否还需要扣钱
        var res = {canDraw:true};
        var limitCash = data.totalCash - data.totalAmount;// 59900
        // limitCash:59900  result.limit_cash_amount:60000
        if (limitCash < limit_cash_amount) {//60000
            var needLimitMoneyTotal = limit_cash_amount - limitCash; //还需限制的总额
            var thisTimeLimitMoney = parseFloat(data.cash) * limit_cash_ratio;   //本次提现本应限制的金额
            res.amount = parseFloat(data.cash) * (1 - limit_cash_ratio);//实际本次应支付提现金额
            if (thisTimeLimitMoney > needLimitMoneyTotal){//说明本次按比例限制的金额，超出了需限制的总额，有一部分金额无需限制
                res.amount = limitCash + parseFloat(data.cash) - limit_cash_amount;
            }
            res.amount = parseFloat(res.amount).toFixed(2);
            //否则需全部按比例限制
        }
        cb(null,res);
    });
}